﻿package leaf.science.ui.camera
{

import caurina.transitions.Tweener;

import flash.display.FrameLabel;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;


public class Camera extends MovieClip
{
	
	private var _frame:Number = 1;
	private var _timer:Timer;
	
	public function Camera()
	{
		stop();
		mouseEnabled = false;
		
		this.frame = 1;
	}
	
	public function spin( time:Number=100 ):void
	{
		if(!_timer || !_timer.running )
		{
			_timer = new Timer( time );
			_timer.addEventListener( TimerEvent.TIMER, onTimer );
			_timer.start(); 
		}
	}
	
	private function onTimer( evt:TimerEvent ):void
	{
//		Console.log( frame + " " + framesLoaded );
		if( frame < framesLoaded )
		{
			frame++;
		}
		//trace( frame + " : " + totalFrames );
		if( frame == totalFrames-1 )
		{
			this.dispatchEvent( new Event( Event.COMPLETE ));
			stop();
			frame = 0;
		}
	}
	
	override public function stop():void
	{
		super.stop();
		if( _timer && _timer.running )
		{
			_timer.removeEventListener( TimerEvent.TIMER, onTimer );
			_timer.stop();
			_timer = null;
		}
	}
	
	private function getFrameLabel( label:String ):FrameLabel
	{
		for( var i:Number=0; i<this.currentLabels.length; i++ )
		{
			var frameLabel:FrameLabel = this.currentLabels[ i ];
			if( label == frameLabel.name )
				return( frameLabel );
			
		}
		return( null );
	}
	
	public function gotoLabel( label:String ):void
	{
		gotoFrame( getFrameLabel( label ).frame );
	}
	
	public function gotoFrame( target:Number ):void
	{
		// find shortest path to target angle
		if( target-currentFrame > 0 && totalFrames+currentFrame-target < target-currentFrame )
			target -= totalFrames;
		else if( target-currentFrame < 0 && totalFrames+target-currentFrame < currentFrame-target )
			target += totalFrames;
		
		// calc animation time depending on path length
		var time:Number = 2 * ( Math.abs( target - currentFrame ) / totalFrames );
		
		// animate
		Tweener.addTween( this, { frame:target, time:time, transition:"easeOutCubic", onComplete:onMotionEnd });
	}
	
	public function onMotionEnd():void {}
	
	
	// cycles in range 0 -> totalFrames (..201)
	public function set frame( f:Number ):void
	{
		if( _frame == f ) return;
		
		f = Math.round( f ) % totalFrames;
		f = ( f < 0 ? f + totalFrames : f );
		_frame = f;
		gotoAndStop( _frame );

		dispatchEvent( new Event( Event.CHANGE ));
	}
	
	public function get frame():Number
	{
		return( _frame );
	}
	
	public function get angle():Number
	{
		return( 360*_frame/totalFrames );
	}
	
	public function set angle( a:Number ):void
	{
		frame = a*totalFrames/360;	
	}
	
}
}